var request = require('request');
const config = require('../config');
const filterApi = require('./filterApi');

class RequestModule {
  /**
   * 执行请求
   * @param {{}} req
   * method ==>'get' or 'post'
   * params ==> api params
   * actionUrl ==> api url
   * {resolve,reject} ==> Promise(resolve,reject)
   */
  doRequest(req) {

    let params = { ...req.params };

    let options = {
      timeout:req.timeout?req.timeout:300000,
      url: req.actionUrl,
      method: req.method,
      json: true,
      headers: Object.assign({
        "Content-Type": "application/json",
        "userInfo": {
          lang: params.lang,
          userId: params.userId,
          tenantId: params.tenantId,
          organizationId: params.organizationId
        },
        'x-bdh-tenant-code': params.user && params.user.tenantCode,
        Authorization: (params.$headers && params.$headers.Authorization) || ''
      }, req.headers)
    }

    //判断是否superuser
    // console.log('==== params.user =====', params.user);
    if (params.user) {
      console.log('==== params.user.biRoleTypeList =====', params.user.biRoleTypeList);
      const isSuperUser = params.user.biRoleTypeList && params.user.biRoleTypeList.indexOf('superuser') > -1;
      const url = req.actionUrl.replace( config.serverUrl_BI, '' );
      if (isSuperUser) {
        if ( filterApi.superFlagUrls.includes(url) ) {
          params.data['superUserFlag'] = 1;
        } else if (filterApi.superDataUrls.includes(url)) {
          params.data = '1';
        }
      }
    }

    //请求之前删除多余api服务无用参数
    delete params.user;
    delete params.actionType;
    params.$headers && delete params.$headers;

    if (req.method.toLowerCase() === "post" || req.method.toLowerCase() === "put") {
      options[options.headers['Content-Type'] === 'application/x-www-form-urlencoded' ? 'form' : 'body'] = params;
    }
    else {
      options.useQuerystring = true;
      options.qs = params;
    }
    request(options, function (err, httpResponse, body) {
      console.log("\n**********[<<<<<<<<<< start >>>>>>>>>>]**********");
      console.log("[" + req.method + "]请求参数====>", params);
      console.log("[" + req.method + "]请求接口====>" + req.actionUrl);
      console.log("[" + req.method + "]请求error====>", err);
      console.log("[" + req.method + "]请求结果====>", body);
      console.log("**********[<<<<<<<<<<< end >>>>>>>>>>>]**********\n");
      if (!err && httpResponse.statusCode === 200) {
        if (body && body.code === 0) {
          req.resolve(body);
        }
        else {
          req.reject(body);
        }
      }
      else {
        req.reject(err || body);
      }
    });
  }
  /**
   * 将请求包装成Promise并返回
   * @param {{}} options 
   * {
   *  method ==>'get' or 'post'
   *  params ==> api params
   *  actionUrl ==> api url
   * }
   */
  doAction(options) {
    return new Promise((resolve, reject) => {
      this.doRequest({
        timeout:options.timeout,
        method: options.method,
        params: options.params,
        actionUrl: options.actionUrl,
        resolve: resolve,
        reject: reject,
        headers: options.headers || {}
      });
    });
  }
  /**
   * 处理响应，返回json结果给页面
   * @param {int} isSuc ==> 1--success or -1--error
   * @param {{}} body ==> api returned data
   * @param {{}} res ==> the response
   */
  handleResponse(isSuc, body, res) {
    //记录日志
    res._resBody = body;
    //删除敏感信息，记录到node日志，不返前台
    if (body) {
      delete body.detail;
      // delete body.traceId;
      delete body.host
    }
    res.json({ status: isSuc, data: body });
  }
  /**
   * 请求完成，直接响应结果
   * @param {{}}} req ==> 
   * { 
   *  method ==> get or post,
   *  params ==> api params,
   *  actionUrl ==> api url
   * } 
   * @param {{}} res ==> the response
   */
  handleRequest(req, res) {
    this.doAction({
      method: req.method,
      params: req.params,
      actionUrl: req.actionUrl,
      timeout:req.timeout
    }).then((body) => {
      this.handleResponse(1, body, res);
    }).catch((err) => {
      this.handleResponse(-1, err, res);
    });
  }
  /**
   * get下载请求
   * @param {string} url 
   * @param {{}} res 
   */
  doDownloadRequestGet(url, res) {
    request(url).pipe(res);
  }
  /**
   * post下载请求
   * @param {string} url 
   * @param {{}} params 
   * @param {Function} callback 
   * @param {{}} res 
   */
  doDownloadRequestPost(options, res) {
    let _params = { ...options.params };
    //请求之前删除多余服务器无用得参数
    delete _params.user;
    delete _params.actionType;
    console.log('请求地址：====》' + options.url);
    console.log('请求参数：====》' + JSON.stringify(_params));
    options.callback = options.callback || function () { };
    request({
      method: "post",
      url: options.url,
      json: true,
      headers: {
        "Content-Type": "application/json"
      },
      body: _params
    }).pipe(res).on('close', options.callback);
  }

  //上传文件到后端
  uploadFile(options, res){
    console.log('请求地址upload file：====》' + options.url);
    console.log('请求参数upload file：====》' + JSON.stringify(options.params));
    return new Promise((resolve, reject) => {
      request.post({
        url: options.url,
        json: true,
        headers: {
          "Content-Type": "multipart/form-data"
        },
        formData: options.params
      }, (err, response, body ) => {
        console.log('请求结果：====》' + body);
        res._resBody = body;
        //删除敏感信息，记录到node日志，不返前台
        if (!err && body) {
          delete body.detail;
          delete body.host
        }
        if(err || !body.success) return reject(body);
        resolve(body);
      });
    })

  }
}

module.exports = RequestModule
